import requests
import os
from PIL import Image, ImageGrab
from aip import AipOcr
import baidu
from baidu.baidu import get_url, get_page
from lxml import etree


def get_screenshot():
    # 1、用grab函数截图，参数为左上角和右下角左标
    # image = ImageGrab.grab((417, 257, 885, 569))
    im = ImageGrab.grab()
    if os.path.exists("image.png"):
        os.remove("image.png")
    else:
        print("要删除的文件不存在！")
    im.save('image.png')


def get_word_by_img():
    # 文字识别
    APP_ID = '16227766'
    API_KEY = 'FgubvnxtReF32vR4jGsS4FY4'
    SECRET_KEY = 'R5YbhWyY2NMF102wRZTwVm9U4hjeAwQG'
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    i = open(r'../new_img_fb.png', 'rb')
    img = i.read()
    img_res = client.basicGeneral(img)
    return img_res


def baidu(question, answers):
    # 进行百度
    resp = get_page(get_url(question))
    # content = etree.HTML(resp)
    for i in range(len(answers)):
        answers[i] = (resp.count(answers[i]), answers[i], i)
    answers.sort(reverse=True)
    return answers

def run():
    while True:
        input("回车答题")
        # get_screenshot()
        img = Image.open('image.png')
        question_img = img.crop((57, 292, 365, 594))
        new_img = Image.new('RGBA', (308, 301))
        new_img.paste(question_img, (0, 0, 308, 302))
        new_img.save('new_img_fb.png')

        info = get_word_by_img()
        answers = [x['words'] for x in info['words_result'][-3:]]
        question = ''.join([x['words'] for x in info['words_result'][:-3]])
        resy = baidu(question, answers)
        print(resy)

if __name__ == '__main__':
    run()

